# -*- coding: utf-8 -*-
import paramiko
import logging
from scrapy.utils.project import get_project_settings
import os
import datetime


class FileCommonClass(object):

    def __init__(self):
        settings = get_project_settings()
        self.file_server_conf = settings.get('FILE_SERVER_CONF')

    # 建立远程服务器连接
    def get_server_conn(self):
        file_server_conf = self.file_server_conf
        host = file_server_conf['host']
        port = file_server_conf['port']
        user_name = file_server_conf['user_name']
        password = file_server_conf['passwd']

        try:
            transport = paramiko.Transport((host, int(port)))
            transport.connect(username=user_name, password=password)
            sftp = paramiko.SFTPClient.from_transport(transport)
            logging.info("Server is connected:")
            return sftp
        except Exception as e:
            logging.error("getServerConn Error:%s" % e)

    @staticmethod
    # 断开服务器连接
    def free_server_conn(sftp):
        sftp.close()
        logging.info("Server is closed:")

    '''
        1.遍历本地文件夹下文件
        2.根据文件名截取目录 companyCode__cityCode__taskId__taskDate__productId.png
        3.判断远程服务器上目录是否存在，不存在则依次创建
        4.判断本地目录待上传文件是否存在，存在则上传至远程服务器
    '''
    def upload_all_by_sftp(self, local_dir, remote_dir):
        logging.info("Inside uploadAllBySftp")
        sftp = self.get_server_conn()
        try:
            files = os.listdir(local_dir)
            # print "files", files
            for f in files:
                file_name_arr = f.split('__')
                for i, file_name in enumerate(file_name_arr):
                    if i == 4:
                        break
                    remote_path = os.path.join(remote_dir, file_name).replace("\\", "/")
                    remote_dir = remote_path
                    try:
                        sftp.stat(remote_path)
                        logging.info("%s File exist" % datetime.datetime.now())
                    except IOError:
                        sftp.mkdir(remote_path)
                        logging.info("%s File not exist" % datetime.datetime.now())
                if os.path.exists(os.path.join(local_dir, f)):
                    logging.info("%s File exists and begin to upload file to %s" % (datetime.datetime.now(), remote_path))
                    sftp.put(os.path.join(local_dir, f), os.path.join(remote_dir, file_name_arr[4]).replace("\\", "/"))
                    logging.info("%s UploadFile success" % datetime.datetime.now())
                else:
                    logging.info("%s File does not exist or has been uploaded!" % datetime.datetime.now())
            self.free_server_conn(sftp)
        except Exception as e:
            logging.error("uploadFile failed:%s" % e)
